import {
  Todo,
  TodoCreate,
  TodoUpdate,
  TodoListResponse,
  TodoResponse,
  TodoStats,
  TodoQueryParams,
  TodoReorderItem,
  ApiResponse
} from '../types/todo'

// API 基础配置
const API_BASE_URL = 'http://localhost:8000'

// 创建一个基础的 fetch 包装函数
async function apiRequest<T>(
  endpoint: string,
  options: RequestInit = {},
  includeAuth: boolean = true
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`
  
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...options.headers as Record<string, string>,
  }
  
  // 添加认证 token（如果需要且存在）
  if (includeAuth) {
    const token = localStorage.getItem('auth_token')
    if (token) {
      headers.Authorization = `Bearer ${token}`
    }
  }
  
  const config: RequestInit = {
    headers,
    ...options,
  }

  try {
    const response = await fetch(url, config)
    
    if (!response.ok) {
      // 如果是认证错误，清除本地token
      if (response.status === 401) {
        localStorage.removeItem('auth_token')
        localStorage.removeItem('user_info')
        window.location.reload() // 重新加载页面以触发登录
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    return data
  } catch (error) {
    console.error(`API request failed: ${url}`, error)
    throw error
  }
}

// 待办事项 API 服务类
export class TodoApiService {
  /**
   * 用户登录
   */
  static async login(username: string, password: string): Promise<any> {
    return apiRequest<any>('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    }, false) // 登录不需要认证header
  }
  /**
   * 获取所有待办事项
   */
  static async getTodos(params?: TodoQueryParams): Promise<TodoListResponse> {
    const searchParams = new URLSearchParams()
    
    if (params?.status) {
      searchParams.append('status', params.status)
    }
    if (params?.priority) {
      searchParams.append('priority', params.priority)
    }
    if (params?.limit) {
      searchParams.append('limit', params.limit.toString())
    }
    
    const query = searchParams.toString()
    const endpoint = query ? `/todos?${query}` : '/todos'
    
    return apiRequest<TodoListResponse>(endpoint)
  }

  /**
   * 根据ID获取单个待办事项
   */
  static async getTodoById(id: number): Promise<TodoResponse> {
    return apiRequest<TodoResponse>(`/todos/${id}`)
  }

  /**
   * 创建新的待办事项
   */
  static async createTodo(todoData: TodoCreate): Promise<TodoResponse> {
    return apiRequest<TodoResponse>('/todos', {
      method: 'POST',
      body: JSON.stringify(todoData),
    })
  }

  /**
   * 更新待办事项
   */
  static async updateTodo(id: number, todoData: TodoUpdate): Promise<TodoResponse> {
    return apiRequest<TodoResponse>(`/todos/${id}`, {
      method: 'PUT',
      body: JSON.stringify(todoData),
    })
  }

  /**
   * 删除待办事项
   */
  static async deleteTodo(id: number): Promise<TodoResponse> {
    return apiRequest<TodoResponse>(`/todos/${id}`, {
      method: 'DELETE',
    })
  }

  /**
   * 批量更新任务排序
   */
  static async reorderTodos(orderUpdates: TodoReorderItem[]): Promise<ApiResponse> {
    return apiRequest<ApiResponse>('/todos/batch/reorder', {
      method: 'PUT',
      body: JSON.stringify(orderUpdates),
    })
  }

  /**
   * 获取统计信息
   */
  static async getStats(): Promise<ApiResponse<TodoStats>> {
    return apiRequest<ApiResponse<TodoStats>>('/todos/stats/summary')
  }

  /**
   * 重置 Mock 数据
   */
  static async resetData(): Promise<ApiResponse> {
    return apiRequest<ApiResponse>('/todos/reset', {
      method: 'POST',
    })
  }

  /**
   * 健康检查
   */
  static async healthCheck(): Promise<{ status: string; message: string }> {
    return apiRequest<{ status: string; message: string }>('/health')
  }
}

// 导出便捷的 API 方法
export const todoApi = {
  // 获取待办事项
  getAll: (params?: TodoQueryParams) => TodoApiService.getTodos(params),
  getById: (id: number) => TodoApiService.getTodoById(id),
  
  // 操作待办事项
  create: (data: TodoCreate) => TodoApiService.createTodo(data),
  update: (id: number, data: TodoUpdate) => TodoApiService.updateTodo(id, data),
  delete: (id: number) => TodoApiService.deleteTodo(id),
  reorder: (orderUpdates: TodoReorderItem[]) => TodoApiService.reorderTodos(orderUpdates),  // 添加重排序方法
  
  // 辅助功能
  getStats: () => TodoApiService.getStats(),
  reset: () => TodoApiService.resetData(),
  health: () => TodoApiService.healthCheck(),
}

// 导出默认实例
export default todoApi